/*
 * Copyright (C) Jahia Ltd. All rights reserved.
 *
 * This software is published under the terms of the Jahia Open Software
 * License version 1.1, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 */
package org.jahia.sqlprofiler.gui;

import javax.swing.JPanel;
import javax.swing.event.ListSelectionListener;
import org.apache.log4j.Category;
import java.text.MessageFormat;
import javax.swing.JEditorPane;
import javax.swing.JTable;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import org.jahia.sqlprofiler.QueryEntry;
import java.util.Date;

/**
 * <p>Title: A panel that displays more details about the currently selected
 * SQL Statement</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: Jahia Ltd</p>
 * @author Serge Huber
 * @version 1.0
 */

class ProfileDetailsPanel extends JPanel
    implements ListSelectionListener {

    private static final Category LOG =
        Category.getInstance(ProfileDetailsPanel.class);

    /** used to format the logging event **/
    private static final MessageFormat FORMATTER = new MessageFormat(
        "<b>Time:</b> <code>{0,time,medium}</code>" +
        "&nbsp;&nbsp;<b>Elapsed time:</b> <code>{1,time,medium}</code>" +
        "&nbsp;&nbsp;<b>Category:</b> <code>{2}</code>" +
        "&nbsp;&nbsp;<b>Connection ID:</b> <code>{3}</code>" +
        "<br><b>Prepared SQL:</b><br>" +
        "{4}<br>" +
        "<b>SQL Statement:</b><br>" +
        "{5}");

    /** the model for the data to render **/
    private final ProfileStatementTableModel mModel;
    /** pane for rendering detail **/
    private final JEditorPane mDetails;

    /**
     * Creates a new <code>DetailPanel</code> instance.
     *
     * @param aTable the table to listen for selections on
     * @param aModel the model backing the table
     */
    ProfileDetailsPanel(JTable aTable, final ProfileStatementTableModel aModel) {
        mModel = aModel;
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createTitledBorder("Details: "));

        mDetails = new JEditorPane();
        mDetails.setEditable(false);
        mDetails.setContentType("text/html");
        add(new JScrollPane(mDetails), BorderLayout.CENTER);

        final ListSelectionModel rowSM = aTable.getSelectionModel();
        rowSM.addListSelectionListener(this);
    }

    /** @see ListSelectionListener **/
    public void valueChanged(ListSelectionEvent aEvent) {
        //Ignore extra messages.
        if (aEvent.getValueIsAdjusting()) {
            return;
        }

        final ListSelectionModel lsm = (ListSelectionModel) aEvent.getSource();
        if (lsm.isSelectionEmpty()) {
            mDetails.setText("Nothing selected");
        } else {
            final int selectedRow = lsm.getMinSelectionIndex();
            final QueryEntry queryEntry = mModel.getStatementDetails(selectedRow);
            final Object[] args = {
                new Date(queryEntry.getTime()),
                new Long(queryEntry.getElapsedTime()),
                escape(queryEntry.getCategory()),
                escape(queryEntry.getConnectionID()),
                escape(queryEntry.getPreparedSQL()),
                escape(queryEntry.getSqlStatement())
            };
            mDetails.setText(FORMATTER.format(args));
            mDetails.setCaretPosition(0);
        }
    }

    ////////////////////////////////////////////////////////////////////////////
    // Private methods
    ////////////////////////////////////////////////////////////////////////////

    /**
     * Escape &lt;, &gt; &amp; and &quot; as their entities. It is very
     * dumb about &amp; handling.
     * @param aStr the String to escape.
     * @return the escaped String
     */
    private String escape(String aStr) {
        if (aStr == null) {
            return null;
        }

        final StringBuffer buf = new StringBuffer();
        for (int i = 0; i < aStr.length(); i++) {
            char c = aStr.charAt(i);
            switch (c) {
                case '<':
                    buf.append("&lt;");
                    break;
                case '>':
                    buf.append("&gt;");
                    break;
                case '\"':
                    buf.append("&quot;");
                    break;
                case '&':
                    buf.append("&amp;");
                    break;
                default:
                    buf.append(c);
                    break;
            }
        }
        return buf.toString();
    }
}
